/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return int整型
     */
    /*
    // 暴力
    int ans = 0;
    int FindPath(TreeNode* root, int sum) {
        if(!root) return ans;
        dfs(root, sum);
        FindPath(root->left, sum);
        FindPath(root->right, sum);
        return ans;
    }
    void dfs(TreeNode* cur, int sum) {
        if(!cur) return ;
        sum -= cur->val;
        if(sum == 0) ans++;
        dfs(cur->left, sum);
        dfs(cur->right, sum);
    }
    */
    // 前缀树
    int recursive(TreeNode* root, int sum, int last){
        if(!root) return 0;
        int ans=0, val=root->val+last;
        if(maps.find(val-sum)!=maps.end()) ans+=maps[val-sum];
        ++maps[val];
        ans+=recursive(root->left, sum, val);
        ans+=recursive(root->right, sum, val);
        --maps[val];
        return ans;
    }
    int FindPath(TreeNode* root, int sum) {
        maps[0]=1;
        return recursive(root, sum, 0);
    }
private:
    unordered_map<int, int>maps;
};